import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import { AtImagePicker } from 'taro-ui';
import { uploadStore } from '@/business/store/upload/upload';
import cssModule from './index.module.scss';
import Taro from '@tarojs/taro';

/**
 * @description 上传文件
 * @author Shawn
 */

interface UploadFileProps {
    count?: number;
    length?: number;
    multiple?: boolean;
    initialUrls?: string[];
    success?: (data: any) => void
}

export default function UploadAvater({ count = 1, length, multiple, initialUrls, success }: UploadFileProps) {
    const [files, setFiles] = useState<{ url: string }[]>(initialUrls ? initialUrls.map(url => ({ url })) : []);

    const compressImage = async (file: File) => {
        const newFile = await Taro.compressImage({
            // @ts-ignore
            src: file.url,
            quality: 80,
        })
        console.log('压缩后路径:', newFile)
        return newFile

    }

    // 上传文件变化
    const handleChange = async (
        newFiles: { url: string }[],
        operationType: 'add' | 'remove',
        index?: number,
    ) => {
        console.log('Files changed:', newFiles, operationType, index);


        if (operationType === 'add') {
            const res1 = await compressImage((newFiles[0] as unknown as File))
            const res = await uploadStore.getState().uploadFiles1(res1.tempFilePath);
            if (success) {
                console.log(res, 'upload res')
                const data = JSON.parse(res!.data)
                console.log(data, 'upload res')
                success([data])
            }
        } else {
            if (success)
                success([])
        }
        setFiles(newFiles);
    };

    const handleAddFile = async () => {
        const openToken = Taro.getStorageSync('openToken');
        const res = await Taro.chooseImage({
            count: 1,
            sourceType: ['album', 'camera'], // 仅从相册选择
        })
        console.log(res, 'res')
        if (res.tempFiles.length) {
            const res1 = await compressImage(({ url: res.tempFiles[0].path }) as unknown as File)
            const uploadRes = await Taro.uploadFile({
                url: `https://baoyouqun.cn/api/files/upload?bucket=`,
                filePath: res1.tempFilePath,
                name: 'file',
                header: {
                    cookie: `satoken=${openToken}`,
                    'content-type': 'multipart/form-data'
                }
            })
            const data = JSON.parse(uploadRes.data)
            const newFiles = [{ url: data.fileUrl, type: data.fileType, fileName: data.originalFileName }];
            setFiles(newFiles);
            if (success) {
                await success(newFiles.map(item => item.url))
            }
        }

    }

    useEffect(() => {
        console.log(initialUrls, 'initialUrls')
        if (initialUrls) {
            setFiles(Array.isArray(initialUrls) ? initialUrls.map((url: any) => ({ url: url.fileUrl ? url.fileUrl : url })) : [])
        }

    }, [initialUrls])

    return (
        <View className={cssModule.container}>
            {
                count && count > 1 && <View className={cssModule.title}>
                    <Text>上传附件（最多{count}张）</Text>
                </View>
            }
            <AtImagePicker
                files={files}
                length={length}
                count={count}
                multiple={multiple}
                onChange={handleChange}
                showAddBtn={files.length < count}
                onImageClick={handleAddFile}

            />
            <View className={cssModule.tips} onClick={handleAddFile}>修改头像</View>
        </View>
    );
}
